package edu.unicen.seo.utils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import edu.unicen.seo.R;

import android.content.Context;
import android.widget.Toast;

public class PersistenceData {

	public static void writeData(Context context, String data, String fileName) {

		FileOutputStream fos = null;
		OutputStreamWriter osw = null;

		try {
			fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
			osw = new OutputStreamWriter(fos);
			osw.write(data);
			osw.flush();
			
		} catch (Exception e) {
			Toast.makeText(context, R.string.dataNotSaved, Toast.LENGTH_SHORT)
					.show();
		} finally {
			try {
				osw.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String readData(Context context, String fileName) {

		FileInputStream fis = null;
		InputStreamReader isr = null;
		char[] inputBuffer = new char[255];
		String data = "";
		
		try {
			fis = context.openFileInput(fileName);
			isr = new InputStreamReader(fis);
			isr.read(inputBuffer);

			data = new String(inputBuffer);			
		}

		catch (Exception e) {
			Toast.makeText(context, R.string.dataNotRead, Toast.LENGTH_SHORT).show();
		} finally {
			try {
				if (fis != null) {
					isr.close();
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return data;
	}
}
